// 云函数入口文件
const cloud = require('wx-server-sdk')
const axios = require('axios');
cloud.init({
  env: cloud.DYNAMIC_CURRENT_ENV
})
const db = cloud.database()
//todo 密钥，提交代码时去掉
//接口相关信息，需申请，请看部署教程deployment.md
const appConfig = {
  app_id: 'app_id',
  app_secret: 'app_secret'
}

// 云函数入口函数
exports.main = async (event, context) => {
  const wxContext = cloud.getWXContext()

  console.log(event)


  //先查询本地
  let tm = new Date().getTime()
  const barcode = event.barcode;
  let result = await db.collection('good')
    .where({
      barcode: barcode
    }).get()

  if (result.data.length > 0) {
    return {
      code: 1,
      data: result.data[0]
    }
  } else {
    var config = {
      method: 'get',
      url: 'https://www.mxnzp.com/api/barcode/goods/details?app_id=' + appConfig.app_id + '&app_secret=' + appConfig.app_secret + '&barcode=' + barcode
    };
    let res = await axios(config)
    console.log(res.data)

    if (res.data.code == 1) {
      var key = "createTime";
      var value = tm
      res.data.data[key] = value
      console.log(res.data.data)
      await db.collection('good').add({
        data: res.data.data
      })
    }


    return res.data
  }





}